<template>
  <div class="p-container">
    <input type="file" ref="upload" accept=".json" @change="executopListchange" id="p_file_executor"
      style="display: none;">
    <div class='r-opreation'>
      <el-tag style="margin-right: 20px;">总数：{{ tableData.length }}</el-tag>
      <el-popconfirm @confirm='removeSelect' confirm-button-text='确定' cancel-button-text='取消' icon-color="red"
        title="确认删除吗？">
        <template #reference>
          <el-button title="删除所选" type="danger" round>
            <el-icon style="margin-right: 4px;">
              <Delete />
            </el-icon>
            删除所选
          </el-button>
        </template>
      </el-popconfirm>

      <el-button style="margin-left:40px" type="primary" @click="uploadJson" round title="初始化文件">
        <el-icon style="margin-right: 4px;">
          <Document />
        </el-icon>
        初始化文件
      </el-button>
      <el-button type="primary" @click="downloadFile" round title="下载文件">
        <el-icon style="margin-right: 4px;">
          <DocumentChecked />
        </el-icon>
        下载文件
      </el-button>
      <el-button type="primary" @click="showJson" round title="查看json">
        <el-icon style="margin-right: 4px;">
          <DocumentCopy />
        </el-icon>
        查看json
      </el-button>

      <el-button v-show="!onSerach" icon="Search" circle @click="onSerach = true"></el-button>

      <el-button v-show="onSerach" class="search">
        <el-icon>
          <Search />
        </el-icon>
        <input v-model="search" placeholder="请输入权限名称">
        <el-icon @click="onSerach = false; search = ''">
          <Close />
        </el-icon>
      </el-button>

    </div>
    <div ref="edit" class="edit">
      <el-table :default-sort="{ prop: 'id', order: 'ascending' }" height='100%' empty-text='数据为空，请上传json，或者右侧新建'
        :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()) || data.sign.toLowerCase().includes(search.toLowerCase()))"
        ref="multipleTable" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="#" width="50">
          <template #default="scope">
            {{ scope.row.index = scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="id">
        </el-table-column>
        <el-table-column prop="name" label="name" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="sign" label="sign" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="userType" label="userType" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="platformType" show-overflow-tooltip>
          <template #default="scope">
            {{
              scope.row.platformType === 3 ? '全部' :
                (scope.row.platformType === 1 ? '区域' :
                  (scope.row.platformType === 2 ? '校级' : (scope.row.platformType === 0 ? '不展示' : '')))
            }}
          </template>
        </el-table-column>
        <el-table-column prop="groupId" label="groupId" show-overflow-tooltip>
          <template #default="scope">
            {{ groupMapData[scope.row.groupId] ? groupMapData[scope.row.groupId].name : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button  @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm @confirm='handleDelete(scope.row)' confirm-button-text='确定' cancel-button-text='取消'
              icon-color="red" title="确认删除吗？">
              <template #reference>
                <el-button  type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-form ref="form" :model="form" label-width="80px" style="text-align: left;">
        <el-form-item label="权限id" prop="id">
          <el-input v-model="form.id" placeholder="权限id"></el-input>
        </el-form-item>
        <el-form-item label="权限name">
          <el-input v-model="form.name" placeholder="权限name"></el-input>
        </el-form-item>
        <el-form-item label="权限sign">
          <el-input v-model="form.sign" placeholder="权限sign"></el-input>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-input v-model="form.date" placeholder="date"></el-input>
        </el-form-item>
        <el-form-item label="模块说明">
          <el-input v-model="form.moduleName" placeholder="moduleName"></el-input>
        </el-form-item>
        <el-form-item label="所属分组">
          <el-select v-model="form.groupId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in groupData" :key="item.id" :label="item.name + ' ' + item.id" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-checkbox-group v-model="form.userTypes">
            <el-checkbox label="教师"></el-checkbox>
            <el-checkbox label="学生"></el-checkbox>
            <el-checkbox label="管理"></el-checkbox>
            <el-checkbox label="游客"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="展示类型">
          <el-radio v-model="form.platformType" :label="3">全部</el-radio>
          <el-radio v-model="form.platformType" :label="1">区域</el-radio>
          <el-radio v-model="form.platformType" :label="2">校级</el-radio>
          <el-radio v-model="form.platformType" :label="0">不展示</el-radio>
        </el-form-item>
        <el-form-item v-show="editType == 'add'">
          <el-button type="primary" @click="addRole">立即创建</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>

        <el-form-item v-show="editType == 'edit'">
          <el-button type="primary" @click="addRole">修改</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="json" v-model="jsonDialogShow" width="600px" center>
      <textarea class="json-txt" :value='jsonInfo'>
  </textarea>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import store from "../store"
import { ElMessage, ElNotify } from 'element-plus'
import { Search, Close, Delete, Document, DocumentChecked, DocumentCopy } from '@element-plus/icons-vue'

export default defineComponent({
  name: "PermissionManager",
  components: {
    Search,
    Close,
    Delete,
    Document,
    DocumentChecked,
    DocumentCopy
  },
  data() {
    return {
      jsonInfo: '',
      jsonDialogShow: false,
      fileName: 'permission.json',
      deleteDialogVisible: true,
      tableData: [],
      editType: 'add',
      form: {
        name: '',
        sign: '',
        id: '',
        index: -1,
        platformType: '',
        moduleName: '',
        userTypes: [],
        userType: '',
        groupId: '',
      },
      multipleSelection: [],
      groupData: [],
      groupMapData: [],
      search: '',
      onSerach: false,
      selectedRows: []
    }
  },
  store,
  methods: {
    resetForm() {
      this.form = {
        name: '',
        sign: '',
        id: '',
        platformType: '',
        moduleName: '',
        date: '',
        userType: '',
        userTypes: [],
        groupId: '',
        index: -1
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    removeSelect() {
      // 使用我们已经定义的selectedRows数组
      let selection = [...this.selectedRows]; // 创建副本以避免删除过程中的索引问题

      // 检查selection是否存在且有数据
      if (!selection || selection.length === 0) {
        return;
      }

      // 创建要删除的ID集合
      const idsToDelete = new Set(selection.map(item => item.id));

      // 从后往前删除，避免索引变化问题
      for (let i = this.tableData.length - 1; i >= 0; i--) {
        if (idsToDelete.has(this.tableData[i].id)) {
          this.tableData.splice(i, 1);
        }
      }

      // 清空选择状态
      this.selectedRows = [];
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].dataIndex = i
      }
      this.save()
      ElMessage({
        message: '已删除',
        type: 'success'
      });
    },
    downloadFile() {
      if (!this.tableData) {
        ElMessage.error('未初始化');
        return
      }

      function fakeClick(obj) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent(
          "click",
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
        obj.dispatchEvent(ev);
      }

      function exportRaw(name, data) {
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([data]);
        var save_link = document.createElementNS(
          "http://www.w3.org/1999/xhtml",
          "a"
        );
        save_link.href = urlObject.createObjectURL(export_blob);
        save_link.download = name;
        fakeClick(save_link);
      }

      let outJson = []
      for (let i = 0; i < this.tableData.length; i++) {
        let item = {
          name: this.tableData[i].name,
          sign: this.tableData[i].sign,
          id: this.tableData[i].id,
          moduleName: this.tableData[i].moduleName,
          date: this.tableData[i].date,
          platformType: this.tableData[i].platformType,
          userType: this.tableData[i].userType,
          groupId: this.tableData[i].groupId
        }

        outJson.push(item)
      }
      exportRaw(
        this.fileName,
        JSON.stringify(outJson, null, 4)
      );
    },
    cancelEdit() {
      this.editType = 'add'
      this.form = {
        name: '',
        sign: '',
        id: '',
        platformType: 1,
        moduleName: '',
        date: '',
        userType: 1,
        userTypes: [],
        groupId: '',
        index: -1
      }
    },
    save() {
      sessionStorage.setItem('pList', JSON.stringify(this.tableData))
      sessionStorage.setItem('pFileName', this.fileName)
    },
    addRole() {
      let utnum = 0;
      if (this.form.userTypes.indexOf('教师') > -1) {
        utnum += 1000;
      }
      if (this.form.userTypes.indexOf('学生') > -1) {
        utnum += 100;
      }
      if (this.form.userTypes.indexOf('管理') > -1) {
        utnum += 10;
      }
      if (this.form.userTypes.indexOf('游客') > -1) {
        utnum += 1;
      }
      if (utnum < 1) {
        utnum = '0000';
      } else if (utnum < 10) {
        utnum = '000' + utnum;
      } else if (utnum < 100) {
        utnum = '00' + utnum;
      } else if (utnum < 1000) {
        utnum = '0' + utnum;
      }
      this.form.userType = utnum + ''
      if (this.form.dataIndex !== undefined && this.form.dataIndex > -1) {
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id === this.form.id && i !== this.form.dataIndex) {
            ElMessage.error('id已存在');
            return
          } else if (this.tableData[i].sign === this.form.sign && i !== this.form.dataIndex) {
            ElMessage.error('sign已存在');
            return
          }
        }
        this.$set(this.tableData, this.form.dataIndex, {
          name: this.form.name,
          sign: this.form.sign,
          id: this.form.id,
          platformType: this.form.platformType,
          moduleName: this.form.moduleName,
          userType: this.form.userType,
          date: this.form.date,
          userTypes: [],
          groupId: this.form.groupId,
          dataIndex: this.form.dataIndex
        })
      } else {
        if (!this.form.id) {
          ElMessage.error('id必填');
          return
        }
        if (!this.form.name) {
          ElMessage.error('name必填');
          return
        }

        if (!this.form.sign) {
          ElMessage.error('sign必填');
          return
        }

        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == this.form.id) {
            ElMessage.error('id已存在');
            return
          } else if (this.tableData[i].sign == this.form.sign) {
            ElMessage.error('sign已存在');
            return
          }
        }
        this.tableData.push({
          name: this.form.name,
          sign: this.form.sign,
          id: this.form.id,
          platformType: this.form.platformType,
          moduleName: this.form.moduleName,
          userType: this.form.userType,
          date: this.form.date,
          userTypes: [],
          groupId: this.form.groupId,
          dataIndex: this.tableData.length
        })
      }

      this.save();

      ElNotify({
        message: '操作成功',
        position: 'top-right',
        type: 'success'
      });
    },
    uploadJson() {
      var inputObj = document.querySelector(
        "#p_file_executor"
      );
      inputObj.click();
    },
    executopListchange() {
      var files = document.querySelector("#p_file_executor").files
      let file = files[0]
      if (file.name.indexOf(".json") != file.name.length - 5) {
        ElMessage.error('不支持的文件格式');
        return;
      }

      var reader = new FileReader(); //新建一个FileReader
      reader.readAsText(file, "UTF-8"); //读取文件
      reader.onload = (evt) => {
        let roles = JSON.parse(evt.target.result)
        if (roles instanceof Array) {
          if (roles.length == 0 || roles[0].name === undefined || roles[0].id === undefined || roles[0].sign === undefined) {
            ElMessage.error('格式有误');
            return
          }
          //this.tableData = roles

          this.tableData.splice(0, this.tableData.length)
          for (let x = 0; x < roles.length; x++) {
            this.tableData.push({
              name: roles[x].name,
              sign: roles[x].sign,
              id: roles[x].id,
              platformType: roles[x].platformType,
              moduleName: roles[x].moduleName,
              userType: roles[x].userType,
              date: roles[x].date,
              userTypes: [],
              groupId: roles[x].groupId,
              dataIndex: x
            })
          }
        } else {
          ElMessage.error('格式有误');
        }
        this.fileName = file.name
        this.save();
        document.querySelector("#p_file_executor").value = ''
      }
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.form.userTypes = []
      if (this.form.userType) {
        let uts = (this.form.userType + '').split('')
        if (uts.length > 0 && uts[uts.length - 1] === '1') {
          this.form.userTypes.push('游客')
        }
        if (uts.length > 1 && uts[uts.length - 2] === '1') {
          this.form.userTypes.push('管理')
        }
        if (uts.length > 2 && uts[uts.length - 3] === '1') {
          this.form.userTypes.push('学生')
        }
        if (uts.length > 3 && uts[uts.length - 4] === '1') {
          this.form.userTypes.push('教师')
        }
      }
      this.editType = 'edit';
    },
    handleDelete(row) {
      this.deleteDialogVisible = false
      this.tableData.splice(row.dataIndex, 1)
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].dataIndex = i
      }
      this.save()
      ElMessage({
        message: '已删除',
        type: 'success'
      });
    },
    fakeClick(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      obj.dispatchEvent(ev);
    },
    showJson() {
      if (!this.tableData) {
        ElMessage.error('未初始化');
        return
      }
      let outJson = []
      for (let i = 0; i < this.tableData.length; i++) {
        outJson.push({
          name: this.tableData[i].name,
          sign: this.tableData[i].sign,
          id: this.tableData[i].id,
          moduleName: this.tableData[i].moduleName,
          date: this.tableData[i].date,
          platformType: this.tableData[i].platformType,
          userType: this.tableData[i].userType,
          groupId: this.tableData[i].groupId
        })
      }
      this.jsonInfo = JSON.stringify(outJson, null, 4)
      this.jsonDialogShow = true
    },
    init() {
      if (sessionStorage.getItem('pList')) {
        this.tableData = JSON.parse(sessionStorage.getItem('pList'))
        this.groupData = JSON.parse(sessionStorage.getItem('gList'))
        this.fileName = sessionStorage.getItem('pFileName')
        if (this.groupData) {
          this.groupData.forEach((item) => {
            this.groupMapData[item.id] = item
          })
        }
      }
    }
  },
  computed: {},
  mounted() {
    this.init()
  }
})
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.p-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.json-txt {
  resize: none;
  width: 100%;
  height: 600px;
  border: none;
  outline: none;
}

.json-txt:hover {
  border: none;
  outline: none;
}

.p-container .el-table {
  overflow-y: auto;
}

.p-container .r-opreation {
  text-align: left;
  margin-bottom: 10px;
}

.p-container .r-opreation .search {
  margin-left: 10px;
  display: inline-flex;
  align-items: center;
  padding: 0 14px;
  border-radius: 40px;
}

.p-container .r-opreation .search input {
  border: none;
  outline: none;
  background-color: transparent;
  margin-left: 4px;
}

.p-container .r-opreation .search i {
  color: rgba(143, 143, 143, 0.933);
}

.p-container .r-opreation .search .el-icon-close {
  cursor: pointer;
}

.p-container .r-opreation .search .el-icon-close:hover {
  color: #f56c6c;
}

.p-container .r-opreation .search:hover {
  border: 1px #bcdeff solid;
}

.p-container .edit {
  display: flex;
  height: 10px;
  flex: 1;
}

.p-container .edit .el-table {
  flex: 1;
  height: 100%;
}

.p-container .edit .el-form {
  width: 400px;
  margin-left: 40px;
}
</style>
